#include "CAN.h"
#include "IO_DEF.h"

/*******************TWAI*******************/

twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT((gpio_num_t)TWAI_TX, (gpio_num_t)TWAI_RX, TWAI_MODE_NORMAL);
twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS();  //Look in the api-reference for other speed sets.
twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();

uint8_t TWAI_CAN_Init(CAN_SPEED_t speed)
{
  switch(speed)
  {
    case CAN_1000K:
      t_config.brp = 4;
    break;
    case CAN_500K:
      t_config.brp = 8;
    break;
    case CAN_250K:
      t_config.brp = 16;
    break;
    case CAN_125K:
      t_config.brp = 32;
    break;
  }
  // Install TWAI driver
  if (twai_driver_install(&g_config, &t_config, &f_config) != ESP_OK) 
  {
    return 0;
  }
  // Start TWAI driver
  if (twai_start() != ESP_OK) 
  {
    return 0;
  }
  // Reconfigure alerts to detect frame receive, Bus-Off error and RX queue full states
  uint32_t alerts_to_enable = TWAI_ALERT_RX_DATA | TWAI_ALERT_ERR_PASS | TWAI_ALERT_BUS_ERROR | TWAI_ALERT_RX_QUEUE_FULL;
  if (twai_reconfigure_alerts(alerts_to_enable, NULL) != ESP_OK) 
  {
    return 0;
  }
  return 1;
}



